package org.gdstash.file;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class GDRandomAccessBuffer extends GDAbstractBuffer {
    private File file;
    private ByteOrder bo;
    private RandomAccessFile raf;

    public GDRandomAccessBuffer(final File file) {
        this.file = file;
        this.bo = ByteOrder.LITTLE_ENDIAN;
        try {
            this.raf = new RandomAccessFile(file, "r");
        } catch (IOException ex) {
            try {
                this.raf.close();
            } catch (IOException ex2) {
            }
        }
    }

    @Override
    public byte[] getByteArray(final int length) throws IOException {
        final byte[] b = new byte[length];
        this.raf.readFully(b);
        return b;
    }

    @Override
    public byte getByte() throws IOException {
        return this.raf.readByte();
    }

    @Override
    public int getInt() throws IOException {
        final byte[] bytes = this.getByteArray(4);
        return ByteBuffer.wrap(bytes).order(this.bo).getInt();
    }

    @Override
    public long getLong() throws IOException {
        final byte[] bytes = this.getByteArray(8);
        return ByteBuffer.wrap(bytes).order(this.bo).getLong();
    }

    @Override
    public short getShort() throws IOException {
        final byte[] bytes = this.getByteArray(2);
        return ByteBuffer.wrap(bytes).order(this.bo).getShort();
    }

    @Override
    public long getPosition() throws IOException {
        return this.raf.getFilePointer();
    }

    @Override
    public void setPosition(final long pos) throws IOException {
        this.raf.seek(pos);
    }

    @Override
    public void close() throws IOException {
        this.raf.close();
    }
}
